import React, { useEffect } from "react";
import { useLocation } from "react-router-dom";

import { appConfig } from "../../router/config";
import { RouteConfig } from "../../router/types";

interface PageTitleProps {
  routes: RouteConfig[];
  children?: React.ReactNode;
}

/**
 * 页面标题管理组件
 * 必须在Router内部使用此组件！
 */
const PageTitle: React.FC<PageTitleProps> = ({ routes, children }) => {
  const location = useLocation();

  useEffect(() => {
    const path = location.pathname;

    const findRouteTitle = (
      routes: RouteConfig[],
      path: string
    ): string | undefined => {
      for (const route of routes) {
        // 构建完整路径
        const routePath = route.path.startsWith("/")
          ? route.path
          : `/${route.path}`;
        const isMatch =
          path === routePath || (path === "/" && routePath === "");

        if (isMatch && route.meta?.title) {
          return route.meta.title;
        }

        // 递归检查子路由
        if (route.children) {
          const childTitle = findRouteTitle(route.children, path);
          if (childTitle) {
            return childTitle;
          }
        }
      }

      return undefined;
    };

    const pageTitle = findRouteTitle(routes, path);

    // 设置文档标题
    if (pageTitle) {
      document.title = `${pageTitle} - ${appConfig.appName}`;
    } else {
      document.title = appConfig.appName;
    }

    // 清理函数
    return () => {
      document.title = appConfig.appName;
    };
  }, [location.pathname, routes]);

  return <>{children}</>;
};

export default PageTitle;
